import 'dart:async';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/position_seek_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/refresh_terminal_bg_music_list_event.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'bean/bg_terminal_music_list_response_bean.dart';
import 'bg_sys_recommend_music_view_model.dart';
import 'notify_bg_music_to_stop_event.dart';

/// 系统推荐音乐列表
class BgSysRecommendMusicPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "BgSysRecommendMusicPage";
  final String hsn;

  const BgSysRecommendMusicPage({Key key, this.hsn}) : super(key: key);
  @override
  BgSysRecommendMusicPageState createState() => BgSysRecommendMusicPageState();

}

class BgSysRecommendMusicPageState
    extends BasePagerState<MusicListBean, BgSysRecommendMusicPage>
    with AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin,
        SingleTickerProviderStateMixin{

  BgSysRecommendMusicViewModel _viewModel;
  StreamSubscription _terminalBgMusicUpdateStreamSubscription;
  StreamSubscription _notifyBgMusicToStopStreamSubscription;

  ///获取state
  static BgSysRecommendMusicPageState of(BuildContext context) {
    final BgSysRecommendMusicPageState result =
    context.findAncestorStateOfType<BgSysRecommendMusicPageState>();
    return result;
  }

  AssetsAudioPlayer _assetsAudioPlayer;
  final List<StreamSubscription> _subscriptions = [];
  bool _isPlaying = false;
  Audio _playingAudio;
  String _currentMusicId;
  AnimationController _controller;
  @override
  void initState() {
    super.initState();
    _viewModel = BgSysRecommendMusicViewModel(this, widget?.hsn);
    _viewModel?.refresh();
    _terminalBgMusicUpdateStreamSubscription =
        VgEventBus.global.on<RefreshTerminalBgMusicListEvent>()?.listen((event) {
          _viewModel?.refresh();
        });

    _assetsAudioPlayer = AssetsAudioPlayer.newPlayer();
    _subscriptions.add(_assetsAudioPlayer.onReadyToPlay.listen((event) {
      VgHudUtils.hide(context);
    }));
    _subscriptions.add(_assetsAudioPlayer.playlistAudioFinished.listen((data) {
      print('playlistAudioFinished : $data');
    }));
    _subscriptions.add(_assetsAudioPlayer.audioSessionId.listen((sessionId) {
      print('audioSessionId : $sessionId');
    }));
    _subscriptions.add(_assetsAudioPlayer.isPlaying.listen((isPlay) {
      setState(() {
        _isPlaying = isPlay??false;
      });
    }));
    _subscriptions.add(_assetsAudioPlayer.current.listen((playing) {
      if(playing != null){
        setState(() {
          _currentMusicId = playing?.audio?.audio?.metas?.id??"";
          print('_currentMusicId : $_currentMusicId');
        });
      }
    }));
    _controller = AnimationController(duration: const Duration(seconds: 1), vsync: this);
    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画从 controller.forward() 正向执行 结束时会回调此方法
        //重置起点
        _controller.reset();
        //开启
        _controller.forward();
      } else if (status == AnimationStatus.dismissed) {
        //动画从 controller.reverse() 反向执行 结束时会回调此方法
      } else if (status == AnimationStatus.forward) {
        //执行 controller.forward() 会回调此状态
      } else if (status == AnimationStatus.reverse) {
        //执行 controller.reverse() 会回调此状态
      }
    });
    _notifyBgMusicToStopStreamSubscription =
        VgEventBus.global.on<NotifyBgMusicToStopEvent>()?.listen((event) {
          if((event.page == 0 || event.page == 2) && _isPlaying){
            _assetsAudioPlayer.pause();
            _controller.stop();
          }
        });
  }

  @override
  void dispose() {
    _terminalBgMusicUpdateStreamSubscription?.cancel();
    _notifyBgMusicToStopStreamSubscription?.cancel();
    _assetsAudioPlayer.dispose();
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      child: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => _viewModel?.refresh(),
        errorOnClick: () => _viewModel.refresh(),
        emptyWidget: _defaultEmptyCustomWidget("暂无内容"),
        errorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
        child: VgPullRefreshWidget.bind(
            state: this,
            viewModel: _viewModel,
            child: _toListPage())
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toListPage(){
    return ListView.separated(
        padding: EdgeInsets.only(
            left: 0,
            right: 0,
            top: 0,
            bottom: getNavHeightDistance(context)
        ),
        itemCount: data?.length ?? 0,
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(index, data?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index) {
          return SizedBox(height: 0);
        });
  }

  Widget _toListItemWidget(int index, MusicListBean itemBean){
    return Column(
      children: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            openPlayer(itemBean);
          },
          child: Container(
            height: 70,
            padding: EdgeInsets.only(right: 15),
            alignment: Alignment.centerLeft,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Row(
              children: [
                _toMusicLogoWidget(itemBean),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      width: ScreenUtils.screenW(context) - 160,
                      alignment: Alignment.centerLeft,
                      child: Text(
                        itemBean?.mname??"-",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 15,
                            color: ThemeRepository.getInstance().getTextColor_D0E0F7()
                        ),
                      ),
                    ),
                    SizedBox(height: 2,),
                    Text(
                      itemBean?.getAuthorAndTime(),
                      style: TextStyle(
                          fontSize: 12,
                          color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                      ),
                    ),
                  ],
                ),
                Spacer(),
                _toUseWidget(itemBean?.id, itemBean?.isInUse()),
              ],
            ),
          ),
        ),
        _toSeekWidget(itemBean),
      ],
    );
  }

  Widget _toMusicLogoWidget(MusicListBean itemBean){
    if(_isPlaying && itemBean.id == _currentMusicId){
      _controller.forward();
      return Container(
        width: 64,
        alignment: Alignment.center,
        child: RotationTransition(
          alignment: Alignment.center,
          turns: _controller,
          child: Image.asset(
            "images/icon_music_play.png",
            width: 46,
            height: 46,
          ),
        ),
      );
    }else{
      return Container(
        width: 64,
        alignment: Alignment.center,
        child: Image.asset(
          "images/icon_music_play.png",
          width: 34,
          height: 34,
        ),
      );
    }
  }

  Widget _toSeekWidget(MusicListBean itemBean){
    return Visibility(
      visible: _isPlaying && itemBean.id == _currentMusicId,
      child: Container(
        height: 50,
        alignment: Alignment.center,
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: _assetsAudioPlayer.builderRealtimePlayingInfos(
            builder: (context, infos) {
              if (infos == null) {
                return SizedBox();
              }
              return Column(
                children: [
                  PositionSeekWidget(
                    currentPosition: infos.currentPosition,
                    duration: infos.duration,
                    seekTo: (to) {
                      _assetsAudioPlayer.seek(to);
                    },
                  ),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          durationToString(infos.currentPosition),
                          style: TextStyle(
                              fontSize: 10,
                              color: Colors.white
                          ),
                        ),
                        Spacer(),
                        Text(
                          durationToString(infos.duration),
                          style: TextStyle(
                              fontSize: 10,
                              color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              );
            }),
      ),
    );
  }

  String durationToString(Duration duration) {
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes =
    twoDigits(duration.inMinutes.remainder(Duration.minutesPerHour));
    String twoDigitSeconds =
    twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));
    return "$twoDigitMinutes:$twoDigitSeconds";
  }


  Widget _toUseWidget(String mid, bool use){
    if(use){
      return Container(
        width: 60,
        height: 28,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            color: Color(0xFF3A3F50)
        ),
        child: Text(
          "已使用",
          style: TextStyle(
              fontSize: 13,
              color: ThemeRepository.getInstance().getHintGreenColor_5E687C()
          ),
        ),
      );
    }else{
      return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          _viewModel.setBgByHsn(context, widget?.hsn, mid);
        },
        child: Container(
          width: 60,
          height: 28,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            border: Border.all(
                color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                width: 0.5),
          ),
          child: Text(
            "使用",
            style: TextStyle(
                fontSize: 13,
                color: Colors.white
            ),
          ),
        ),
      );
    }
  }

  void openPlayer(MusicListBean itemBean) async {
    VgEventBus.global.send(new NotifyBgMusicToStopEvent(1));
    if(itemBean?.id == _currentMusicId){
      if(_isPlaying){
        _assetsAudioPlayer.pause();
      }else{
        _assetsAudioPlayer.play();
      }
      return;
    }
    VgHudUtils.show(context, "加载中");
    _playingAudio = Audio.network(
      itemBean.murl,
      metas: Metas(
        id: itemBean.id,
        title: itemBean.mname,
        artist: itemBean.author,
        album: itemBean.author,
      ),
      cached: true
    );
    setState(() {});
    try {
      await _assetsAudioPlayer.open(
        _playingAudio,
        autoStart: true,
        showNotification: false,
        playInBackground: PlayInBackground.disabledRestoreOnForeground,
        audioFocusStrategy: AudioFocusStrategy.request(
            resumeAfterInterruption: true,
            resumeOthersPlayersAfterDone: true),
        headPhoneStrategy: HeadPhoneStrategy.pauseOnUnplug,
      );
    } catch (e) {
      print(e);
    }
  }


  @override
  bool get wantKeepAlive => true;
}
